package com.service.supply;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.InquiryMapper;
import com.dao.purchase.OrderDao;
import com.dao.purchase.SupplyDealMapper;
import com.dao.purchase.SupplyDealMmMapper;
import com.dao.purchase.SupplyOfferMapper;
import com.dao.purchase.SupplyOfferMmMapper;
import com.dao.supply.InfoMapper;
import com.dao.supply.UserMapper;
import com.dao.sys.FileDao;
import com.enums.DictEnum;
import com.model.purchase.OrderModel;
import com.model.purchase.PurchaseInquiry;
import com.model.purchase.PurchaseInquiryVO;
import com.model.purchase.PurchaseProgram;
import com.model.purchase.PurchaseProgramMm;
import com.model.purchase.PurchaseSupplyDeal;
import com.model.purchase.PurchaseSupplyDealMm;
import com.model.purchase.PurchaseSupplyOffer;
import com.model.purchase.PurchaseSupplyOfferMm;
import com.model.purchase.PurchaseSupplyOfferVO;
import com.model.supply.SupplyInfoModel;
import com.model.supply.SupplyUserModel;
import com.model.sys.FileModel;
import com.model.sys.SysDict;
import com.service.sys.SysDictService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * 供应商报价管理
 *
 * @author chenjun
 */
@Service
public class OfferService {

	static final Logger logger = LoggerFactory.getLogger(OfferService.class);

	@Autowired
	InfoService infoService;
	@Autowired
	SupplyOfferMapper supplyOfferMapper;
	@Autowired
	UserMapper userMapper;
	@Autowired
	SupplyOfferMmMapper supplyOfferMmMapper;
	@Autowired
	SupplyDealMapper supplyDealMapper;
	@Autowired
	SupplyDealMmMapper supplyDealMmMapper;
	@Autowired
	FileDao fileDao;
	@Autowired
	OrderDao orderDao;
	@Autowired
	InquiryMapper inquiryMapper;
	@Autowired
	InfoMapper infoMapper;

	/**
	 * 查询报价列表
	 *
	 * @param map
	 * @return
	 */
	public HttpResult selectOfferList(Map<String, Object> map) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes == null) {
			return HttpResult.error("当前会话不存在！");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在");
		}
		map.put("infId", supplyUserModel.getInfId());
		EasyuiUtils.addPageNum(map);
		EasyuiUtils.addFilter(map);

		map.put("inqMode", "线上报价");

		List<PurchaseSupplyOffer> purchaseSupplyOffers = supplyOfferMapper.selectSupplyOfferList(map);
		int count = supplyOfferMapper.selectSupplyOfferListCount(map);

		HttpResult httpResult = new HttpResult();
		httpResult.setRows(purchaseSupplyOffers);
		httpResult.setTotal(count);
		return httpResult;
	}

	public HttpResult selectBidList(Map<String, Object> map) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes == null) {
			return HttpResult.error("当前会话不存在！");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在");
		}
		map.put("infId", supplyUserModel.getInfId());
		EasyuiUtils.addPageNum(map);
		EasyuiUtils.addFilter(map);

		List<OrderModel> list = orderDao.selectList(map);
		int count = orderDao.selectListCount(map);

		HttpResult httpResult = new HttpResult();
		httpResult.setRows(list);
		httpResult.setTotal(count);
		return httpResult;
	}

	public HttpResult selectBidMmList(String resId, String infId) {
		if (!StringUtils.isNotNull(resId) || !StringUtils.isNotNull(infId)) {
			return HttpResult.error("参数不能为空!");
		}
		HttpResult httpResult = new HttpResult();
		List<PurchaseSupplyDealMm> purchaseSupplyDealMm = supplyDealMmMapper.loadByInfIdAndResId(resId, infId);
		httpResult.setRows(purchaseSupplyDealMm);
		return httpResult;
	}

	public void exportBidMmList(Map<String, Object> queryMap, HttpServletResponse response) {

		String resId = queryMap.get("resId").toString();
		String infId = queryMap.get("infId").toString();

		List<PurchaseSupplyDealMm> purchaseSupplyDealMm = supplyDealMmMapper.loadByInfIdAndResId(resId, infId);

		logger.info("exportProgram:{}", purchaseSupplyDealMm);
		try {
			EasyExcel.write(response.getOutputStream(), PurchaseSupplyDealMm.class).sheet("模板")
					.doWrite(purchaseSupplyDealMm);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	/**
	 * 查询报价明细列表
	 *
	 * @param map
	 * @return
	 */
	public HttpResult selectOfferMmList(String inqId) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes == null) {
			return HttpResult.error("当前会话不存在！");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在");
		}
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("inqId", inqId);
		hashMap.put("infId", supplyUserModel.getInfId());
		List<PurchaseSupplyOfferMm> purchaseSupplyOfferMms = supplyOfferMmMapper.selectAll(hashMap);
		HttpResult httpResult = new HttpResult();
		httpResult.setRows(purchaseSupplyOfferMms);
		return httpResult;
	}

	/**
	 * 保存报价明细
	 *
	 * @param map
	 * @return
	 */
	@Transactional
	public HttpResult saveOfferMm(PurchaseSupplyOfferVO purchaseSupplyOfferVO) {
		if (purchaseSupplyOfferVO == null || purchaseSupplyOfferVO.getPurchaseSupplyOfferMms() == null) {
			return HttpResult.error("请求参数为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(purchaseSupplyOfferVO.getInqId());
		if (StringUtils.isNotNull(purchaseInquiry.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可操作!");
		}
		if (purchaseSupplyOfferVO.getInqStartTime().compareTo(DateUtils.getCurrentTime()) > 0) {
			return HttpResult.error("报价未开始，不可操作!");
		}
		if (purchaseSupplyOfferVO.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes == null) {
			return HttpResult.error("当前会话不存在！");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在！");
		}

		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("infId", supplyUserModel.getInfId());
		List<SupplyInfoModel> infoModels = infoMapper.selectList(infoHashMap);
		if (infoModels.size() == 0) {
			return HttpResult.error("供应商不存在");
		}

		if (purchaseSupplyOfferVO.getInqOfrNum().doubleValue() <= 0
				|| purchaseSupplyOfferVO.getInqOfrTotalPrice().doubleValue() <= 0) {
			return HttpResult.error("报价数量和价格不能为空！");
		}
		int result = 0;
		// 如果为提交
		if (purchaseSupplyOfferVO.getStatus().equals(Global.YES + "")) {
			// 设置提交时间
			purchaseSupplyOfferVO.setInqOfrTime(DateUtils.getCurrentTime());
			String mailString = infoModels.get(0).getInfMail();
			if (StringUtils.isNullOrEmpty(mailString)) {
				return HttpResult.error("请先在档案信息维护正确邮箱!");
			}
		}
		// 主表保存
		purchaseSupplyOfferVO.setInfId(supplyUserModel.getInfId());
//		purchaseSupplyOfferVO.setInfContact(supplyUserModel.getUserName());
//		purchaseSupplyOfferVO.setInfContactTel(supplyUserModel.getUserTel());		
		result = supplyOfferMapper.update(purchaseSupplyOfferVO);
		// 明细报价保存
		for (PurchaseSupplyOfferMm purchaseSupplyOfferMm : purchaseSupplyOfferVO.getPurchaseSupplyOfferMms()) {
			if ((result += supplyOfferMmMapper.updateByPrimaryKey(purchaseSupplyOfferMm)) == 0) {
				result += supplyOfferMmMapper.insert(purchaseSupplyOfferMm);
			}
		}
		HttpResult httpResult = new HttpResult();

		if (result > 0) {
			httpResult.setData(purchaseSupplyOfferVO);
			httpResult.setMsg(purchaseSupplyOfferVO.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			return httpResult;
		} else {
			return HttpResult.error(purchaseSupplyOfferVO.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
	}

	@Transactional
	public HttpResult backInquiryOffer(String inqId, String infId) {
		if (inqId == null || infId == null) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(inqId);
		if (StringUtils.isNotNull(purchaseInquiry.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可回退!");
		}

		int result = 0;
		PurchaseSupplyOffer supplyOffer = supplyOfferMapper.load(inqId, infId);
		supplyOffer.setStatus(Global.NO + "");
		result = supplyOfferMapper.update(supplyOffer);

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("回退成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("回退失败！");
		}
		return httpResult;
	}

	/**
	 * 提交报价
	 *
	 * @param map
	 * @return
	 */
	public HttpResult commitOffer(PurchaseSupplyOfferVO purchaseSupplyOfferVO) {
		if (purchaseSupplyOfferVO == null || purchaseSupplyOfferVO.getPurchaseSupplyOfferMms() == null) {
			return HttpResult.error("请求参数为空");
		}
		int result = 0;
		// 主表保存
		result = supplyOfferMapper.update(purchaseSupplyOfferVO);
		// 明细报价保存
		for (PurchaseSupplyOfferMm purchaseSupplyOfferMm : purchaseSupplyOfferVO.getPurchaseSupplyOfferMms()) {
			if ((result += supplyOfferMmMapper.updateByPrimaryKey(purchaseSupplyOfferMm)) > 0) {
				result += supplyOfferMmMapper.insert(purchaseSupplyOfferMm);
			}
		}

		if (result > 0) {
			return HttpResult.ok("保存成功");
		} else {
			return HttpResult.error("保存失败");
		}
	}

	public void exportOfferMm(Map<String, Object> queryMap, HttpServletResponse response) {
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
//		queryMap.put("inqId", inqId);
		queryMap.put("infId", supplyUserModel.getInfId());
		List<PurchaseSupplyOfferMm> purchaseSupplyOfferMms = supplyOfferMmMapper.selectAll(queryMap);

		logger.info("exportProgram:{}", purchaseSupplyOfferMms);
		try {
			EasyExcel.write(response.getOutputStream(), PurchaseSupplyOfferMm.class).sheet("模板")
					.doWrite(purchaseSupplyOfferMms);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	@Value("${filepath}")
	String basePath;
	@Autowired
	SysDictService sysDictService;

	/**
	 * 导入报价信息
	 * 
	 * @param map
	 * @return
	 */
	public HttpResult importMM(Map<String, Object> map) {
		List<FileModel> fileModels = fileDao.selectList(map);
		if (fileModels == null || fileModels.size() == 0) {
			return HttpResult.error("导入文件不存在!");
		}

		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		if (supplyUserModel == null) {
			return HttpResult.error("用户不存在");
		}
		PurchaseSupplyOffer purchaseSupplyOfferVO = supplyOfferMapper.load(map.get("fileRow").toString(),
				supplyUserModel.getInfId());
		if (purchaseSupplyOfferVO.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}
		List<SysDict> dicList = sysDictService.queryItemByTypeName(DictEnum.taxString);

		FileModel fileModel = fileModels.get(0);
		String fileName = basePath + "/" + fileModel.getFileUrl() + "/" + fileModel.getFileId() + "-"
				+ fileModel.getFileName();
		List<String> errList = new ArrayList<String>();
		EasyExcel.read(fileName, PurchaseSupplyOfferMm.class, new PageReadListener<PurchaseSupplyOfferMm>(dataList -> {
			for (PurchaseSupplyOfferMm demoData : dataList) {
				if (demoData.getPlanId() == null) {
					errList.add("计划编码：" + demoData.getMmDetail() + "为空");
					break;
				}
				PurchaseSupplyOfferMm purchaseSupplyOfferMm = supplyOfferMmMapper.selectByPrimaryKey(
						supplyUserModel.getInfId(), map.get("fileRow").toString(), demoData.getPlanId());
				if (purchaseSupplyOfferMm == null) {
					errList.add("计划编码：" + demoData.getMmDetail() + "不存在");
					break;
				}
				if (demoData.getInqOfrNum() == null) {
					errList.add("物资：" + demoData.getMmDetail() + "报价数量为空");
					break;
				}
				purchaseSupplyOfferMm.setInqOfrNum(demoData.getInqOfrNum());
				if (demoData.getInqOfrUnitPrice() == null) {
					errList.add("物资：" + demoData.getMmDetail() + "报价单价为空");
					break;
				}
				purchaseSupplyOfferMm.setInqOfrUnitPrice(demoData.getInqOfrUnitPrice());
				purchaseSupplyOfferMm
						.setInqOfrTotalPrice(demoData.getInqOfrNum().multiply(demoData.getInqOfrUnitPrice()));
				purchaseSupplyOfferMm.setInqDeliverDate(demoData.getInqDeliverDate());
				SysDict sysDict = existsDic(demoData.getInqTaxRate(), dicList);
				if (sysDict == null) {
					errList.add("计划编码：" + demoData.getPlanId() + "税率录入不正确");
				} else {
					purchaseSupplyOfferMm.setInqTaxNum(sysDict.getDicValue());
//					BigDecimal taxBigDecimal = new BigDecimal(sysDict.getDicName());
					purchaseSupplyOfferMm.setInqTaxRate(sysDict.getDicName());
				}
				supplyOfferMmMapper.updateByPrimaryKey(purchaseSupplyOfferMm);
			}
		})).sheet().doRead();
		if (errList.size() > 0) {
			HttpResult httpResult = new HttpResult();
			httpResult.setData(errList);
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			return httpResult;
		}
		return HttpResult.ok("导入成功");
	}

	public SysDict existsDic(String dicString, List<SysDict> dicList) {
		SysDict flag = null;
		for (SysDict sysDict : dicList) {
//			BigDecimal taxBigDecimal = new BigDecimal(sysDict.getDicName());
			if (sysDict.getDicName().equals(dicString)) {
				return sysDict;
			}
		}
		return flag;

	}
}
